package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.*;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.lzx.iteam.bean.AddressData;

import java.util.ArrayList;

/**
 * Created by Megan on 16/4/13.
 */
public class BaiduMapSearchActivity extends Activity implements
        OnGetPoiSearchResultListener, OnGetSuggestionResultListener, View.OnClickListener {

    private EditText mEtSearch;
    private TextView mTvCancle;
    private ListView mLvList;
    private PoiSearch mPoiSearch = null;
    private SuggestionSearch mSuggestionSearch = null;
    private SearchAdapter mAdapter;
    private ArrayList<AddressData> addressDatas=new ArrayList<AddressData>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baidu_map_search_layout);
        initViews();

    }


    private void initViews() {

        // 初始化搜索模块，注册搜索事件监听
        /**
         * 百度地图SDK提供三种类型的POI检索：周边检索、区域检索和城市内检索
         * 暂时没用
         * mPoiSearch.searchInCity((new PoiCitySearchOption()).city(editCity.getText().toString()).keyword(editSearchKey.getText().toString()).pageNum(load_Index));
         * mPoiSearch
         */
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
        mTvCancle = (TextView) findViewById(R.id.tv_map_search_input_cancle);
        mEtSearch = (EditText) findViewById(R.id.et_map_search_input);
        mLvList = (ListView) findViewById(R.id.lv_baidu_map_search_list);

        mAdapter = new SearchAdapter();
        mLvList.setAdapter(mAdapter);

        mLvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent();
                intent.putExtra("address",addressDatas.get(i));
                setResult(RESULT_OK,intent);
                finish();
            }
        });
        mTvCancle.setOnClickListener(this);
        /**
         * 当输入关键字变化时，动态更新建议列表
         */
        mEtSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                if (cs.length() <= 0) {
                    addressDatas.clear();
                    mAdapter.notifyDataSetChanged();
                    return;
                }

                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
                /*  String city = "北京";
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city(city));*/
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city(""));
            }
        });
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if (poiResult == null
                || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(BaiduMapSearchActivity.this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
          /*  mBaiduMap.clear();
            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(poiResult);
            overlay.addToMap();
            overlay.zoomToSpan();*/
            return;
        }
        if (poiResult.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : poiResult.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            Toast.makeText(BaiduMapSearchActivity.this, strInfo, Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(BaiduMapSearchActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(BaiduMapSearchActivity.this, poiDetailResult.getName() + ": " + poiDetailResult.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {
            return;
        }
        addressDatas.clear();
        for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
            if (info.key != null&&info.pt!=null) {
                AddressData addressData=new AddressData();
                addressData.setKey(info.key);
                addressData.setCity(info.city);
                addressData.setDistrict(info.district);
                addressData.setLatitude(info.pt.latitude);
                addressData.setLongitude(info.pt.longitude);
                addressData.setUid(info.uid);
                addressDatas.add(addressData);
                Log.d("BaiduMapSearchActivity", "联想词key:" + info.key + ",联想词city:" + info.city + ",联想结果所在行政区:" + info.district + ",联想结果坐标点:" + info.pt + ",联想结果uid:" + info.uid);
            }
        }
        mAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPoiSearch.destroy();
        mSuggestionSearch.destroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_map_search_input_cancle:
                finish();
                break;
        }
    }


    private class SearchAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return addressDatas.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return addressDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(BaiduMapSearchActivity.this).inflate(R.layout.item_map_search,
                        parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.text.setText(addressDatas.get(position).getKey());
            holder.city.setText(addressDatas.get(position).getCity()+"-"+addressDatas.get(position).getDistrict());

            return convertView;
        }
    }

    private class ViewHolder {
        public TextView text;
        public TextView city;

        public ViewHolder(View view) {
            text = (TextView) view.findViewById(R.id.tv_map_search_text);
            city = (TextView) view.findViewById(R.id.tv_map_search_city);
        }
    }
}
